<template>
  <div v-loading="loading" class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
      style="display: flex; flex-wrap: nowrap;">
      <el-form-item label="上传人" prop="f0909" style="display: flex; flex-wrap: nowrap;">
        <el-input style="width: 14vw" v-model="queryParams.f0909" placeholder="请输入上传人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文件名称" prop="f0902" style="display: flex; flex-wrap: nowrap;">
        <el-input style="width: 14vw" v-model="queryParams.f0902" placeholder="请输入文件名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item style="margin: 0 0 0 30vw;">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-plus" size="mini" @click="handleAdd">上传文件</el-button>
        <el-button style="background-color: black; color: white;" @click="download">批量下载</el-button>
        <!-- v-hasPermi="['t03:t03:export']" -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="T09List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上传人" align="center" prop="f0909" />
      <el-table-column label="文件名称" align="center" prop="f0902" />
      <el-table-column label="文件格式" align="center" prop="f0904" />
      <el-table-column label="用户上传时间" align="center" prop="f0905" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="download(scope.row)">下载文档</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改知识库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-upload class="upload-demo" ref="upload" action="#" :before-upload="beforeUpload"
          :on-change="handleFileChange" multiple :auto-upload="false" :limit="10" :on-exceed="handleExceed"
          :accept="fileType" :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf/png/jpg/xlsx文件，且不超过1万字</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportT09 } from "@/api/T09/T09";
import { listT09, addT09 } from "@/api/knowledge_manage/T09";

export default {
  name: "T09",
  dicts: ['zsk_execution_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库表格数据
      T09List: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        f0909: null,
        f0906: null,
        f0902: null,
      },
      // 表单参数
      form: {},
      // 上传文件类型
      fileType: ".doc,.docx,.pdf,.png,.jpg,.xlsx",
      fileList: [], // 用于存储上传的文件列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询知识库列表 */
    getList() {
      this.loading = true;
      listT09(this.queryParams).then(response => {
        this.T09List = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    reset() {
      this.form = {
        f0901: null,
        f0601: null,
        f0301: null,
        f0902: null,
        f0903: null,
        f0904: null,
        f0905: null,
        f0906: null,
        f0907: null,
        f0909: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.f0901)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识库管理";
    },
    beforeUpload(file) {
      const fileExtension = file.name.split('.').pop().toLowerCase();
      console.log("文件扩展名", fileExtension);

      if (!this.fileType.includes(`.${fileExtension}`)) {
        this.$message.error('仅允许上传 .doc,.docx,.pdf,.png,.jpg,.xlsx文件！');
        return Promise.reject();
      }

      // 确保file.raw存在
      if (!file.raw) {
        file.raw = file;
      }

      return false; // 阻止自动上传
    },
    // 文件上传函数
    handleFileChange(file, fileList) {
      console.log("文件改变", file, fileList);
      if (!file.raw && file.raw !== file) {
        // 如果raw不存在，将原始File对象赋值给raw
        file.raw = file;
      }

      this.fileList = fileList.map(item => {
        // 确保每个文件都有raw属性
        if (!item.raw && item.raw !== item) {
          item.raw = item;
        }
        return item;
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件`);
    },
    /** 提交按钮 */
    submitForm() {
      this.uploadFiles();
      this.open = false;
    },
    //文件上传
    uploadFiles() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择要上传的文件');
        return;
      }

      const formData = new FormData();

      // 遍历文件列表，将每个文件添加到FormData中
      this.fileList.forEach((file, index) => {
        // 使用files[]数组形式传递多个文件
        formData.append('files', file.raw);

        // 可以添加额外的文件信息
        formData.append(`fileInfo[${index}].name`, file.name);
        formData.append(`fileInfo[${index}].type`, file.raw.type);
      });

      // 添加其他表单数据（如果需要）
      if (this.form.f0901) {
        formData.append('f0901', this.form.f0901);
      }

      // 打印FormData内容以便调试
      console.log('FormData内容:');
      for (let [key, value] of formData.entries()) {
        console.log(key, value);
      }

      // 发送请求
      addT09(formData)
        .then(response => {
          this.$message.success('文件上传成功');
          this.open = false;
          this.getList();
          this.fileList = [];
        })
        .catch(error => {
          console.error('上传错误:', error);
          this.$message.error('文件上传失败');
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
    },
    async download(row) {
      this.loading = true;
      // const ids = row.f0901 || this.ids;
      const ids = row.f0901 ? [row.f0901] : this.ids;
      // console.log(ids)
      await exportT09(ids,
        {
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
          },
        }).then(res => {
          console.log(111, res.data)
          let filename = '知识库';
          const url = window['URL'].createObjectURL(res);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = filename; // 确保文件名与后端设置的一致
          document.body.appendChild(a);
          a.click();
          window['URL'].revokeObjectURL(url);
          document.body.removeChild(a);
        }).finally(() => {
          this.loading = false;
        })
    },
  }
};
</script>
<style>
.el-tag-common-red {
  background-color: #ffebee;
  /* 浅红色背景 */
  border-color: #d32f2f;
  /* 深红色边框 */
  color: #b71c1c;
  /* 深红色字体 */
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 24px;
  padding: 0 9px;
  font-size: 12px;
  line-height: 1;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

.el-tag-red {
  /* 重写.el-tag-common的样式以使用红色主题 */
  background-color: #ffebee;
  /* 浅红色背景 */
  border-color: #d32f2f;
  /* 深红色边框 */
  color: #b71c1c;
  /* 深红色字体 */
  /* 如果需要特别指定.el-tag-green独有的样式，可以在这里添加 */
}

.el-tag-common-green {
  background-color: #E8FFEA;
  /* 浅绿色背景 */
  border-color: #98e69e;
  /* 深一些的绿色边框 */
  color: #66ffcc;
  /* 更亮的绿色字体 */
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 24px;
  padding: 0 9px;
  font-size: 12px;
  line-height: 1;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

.el-tag-green {
  /* 假设您希望.el-tag-green与.el-tag-common完全一致，或者您可以指定不同的绿色 */
  background-color: #e0f2f1;
  /* 浅绿色背景 */
  border-color: #b2d7d2;
  /* 深一些的绿色边框 */
  color: #4fdc4f;
  /* 更亮的绿色字体 */
}
</style>
